package com.bos.controller;

import com.bos.controller.base.BaseController;
import com.bos.controller.base.imp.BaseControllerImp;
import com.bos.domain.Role;
import com.bos.domain.User;
import com.bos.service.IUserService;
import com.bos.utils.BOSUtil;
import com.bos.utils.MD5Utils;
import com.bos.utils.PageBean;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @author Administrator
 */

@Controller
//@Scope("prototype")
public class UserController  extends BaseControllerImp<User> implements BaseController<User> {

    @Autowired
    IUserService userService;

    @Autowired
    public UserController(PageBean pageBean){
        super(pageBean);
    }


    /**用户登录
     * */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User loginUser, String checkcode, Model model)  {

        String validateCode = (String) BOSUtil.getSession().getAttribute("key");
        if (StringUtils.isNotBlank(validateCode) && validateCode.equals(checkcode)) {
            //使用shiro框架进行认证
            //获得shiro"当前用户对象"subject，状态为未认证
            Subject  subject = SecurityUtils.getSubject();
            //创建认证令牌
            AuthenticationToken token = new UsernamePasswordToken(loginUser.getUsername(), MD5Utils.md5(loginUser.getPassword()));
            try {
                subject.login(token);
                /*按照捕获的异常类型进行信息提示*/
            }catch (UnknownAccountException e){
                e.printStackTrace();
                model.addAttribute("message", "用户名或密码错误");
                return "login";
            }catch (IncorrectCredentialsException e){
                e.printStackTrace();
                model.addAttribute("message", "用户名或密码错误");
                return "login";
            }
            BOSUtil.getSession().setAttribute("user",subject.getPrincipal());
            return "redirect:/home";
        }
        else {
            model.addAttribute("message", "验证码错误");
            return "login";
        }
    }


    /**登出账户
    * */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(){
//        BOSUtil.getSession().invalidate();
        //使用shiro的登出功能,shiro会自己清除当前用户的session
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }


    /**编辑密码
    * */
    @RequestMapping(value = "/editPwd",method = RequestMethod.POST)
    @ResponseBody
    public String editPwd(String newPwd){
        User user = BOSUtil.getUser();
        boolean success=true;
        try {
            userService.editPassword(user.getId(),newPwd);
        }catch (Exception e){
            success=false;
            e.printStackTrace();
            throw new RuntimeException();
        }
        return String.valueOf(success);
    }

    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public String addRole(User user,String [] roleIds){
        userService.save(user,roleIds);
        return "redirect:/page/admin/userlist";
    }

    @RequestMapping(value = "/UserPageQuery",method = RequestMethod.GET)
    @ResponseBody
    public String funtionPageQuery(int page ,int rows){
        //将当前页号和页面大小至于session域中，以便刷新时保持不变
        BOSUtil.getSession().setAttribute("UserPage",page);
        BOSUtil.getSession().setAttribute("UserRows",rows);
        setPageAndRows(page,rows);
        userService.pageQuery(super.pageBean);
        String json = java2jsonAndDate(new String[]{"currentPage","pageSize","detachedCriteria",
                "noticebills","roles"});
        return json;
    }

}
